import SessionUserUtil from '../../../data/session/sessionUser'
import SessionUtil, { JxbHttpClient, Session } from '../../../data/session/session';
import SessionSellingServerUtil from '../../../data/session/sessionSellingServer';
import InteractionUtil from '../../../shell/ui/interaction';
import LangUtil from '../../../utils/lang';

var Common = require('../../../utils/common.js');
var fun_base64 = require("../../../utils/base64.js")

Page({
  data: {
    token: '',
    productsList: {},
    userName: '',
    sumMemberPrice: '',
    cutMoney: 0,
    sumShopPrice: '',
    sumcount: 0,
    cartIds: 0,
    addressId: null,
    dilivery: '快递',
    coupon_name: "暂无可用优惠券",
    invoCustName: '',
    wx_invoice_type: '',
    wx_invoice_title: '',
    wx_invoice_tax_number: '',
    wx_invoice_company_address: '',
    wx_invoice_telephone: '',
    wx_invoice_bank_name: '',
    wx_invoice_bank_account: '',
    deliveryId: 2,
    pay_amount_type: 1,
    will_pay_amount: 0.00,
    itemInfo: {
      'been': []
    },
    userId: 0,
    isHidePayAmountType: true,
    payAmountTypeId: 1,
    tag: false,
    payAmountTypeList: {
      1: 'cblue',
      5: ''
    },
    payAmountType: '全额付款',
    mark: '',
    total_balance: {},
    ifshowS: false,
    point: {},
    useScore: false,
    score: 0,
    scoce_money: 0,
    saleMode: 1
  },
  onLoad: function(options) {
    if (options.deliveryId == 999999999) {
      this.setData({
        dilivery: '自提',
        deliveryId: 999999999
      })
    }
    if (options.checkedlis) {
      this.setData({
        checkedlis: options.checkedlis
      })
    }
    let lang = {
      shopping_points : LangUtil.translate('shopping_points'),
      server_title : LangUtil.translate('server_title'),
    };
    var pay = wx.getStorageInfoSync("pay"),
      total_balance = wx.getStorageSync("total_balance");
    this.setData({
      lang,
      total_balance: total_balance,
      payAmountTypeId: pay.payAmountTypeId ? pay.payAmountTypeId : this.data.payAmountTypeId,
      payAmountType: pay.payAmountType ? pay.payAmountType : this.data.payAmountType,
    })
    SessionUtil.getInstance().then(()=>{
      wx.setNavigationBarTitle({
        title: '订单确认'
      })
      /**获取当前顾问信息 */
      Common.showContips(this);
    })
  },
  onShow: function() {
    getApp().getSaleMode().then(res => {
      this.setData({
        saleMode: res
      })
    })
    let waddress = wx.getStorageSync("waddress"),
    addressId = wx.getStorageSync("addressId");
    if(waddress && addressId){
      this.setData({
        waddress: waddress,
        addressId: addressId
      })
    }
    SessionUtil.getInstance().then(()=>{
      let sessionUser = SessionUserUtil.getInstanceSync(),
      sellingServer = SessionSellingServerUtil.getInstanceSync();
      this.setData({
        salesman:{
          vCardId: sellingServer.getTheVCardSync().id,
          salesmanId: sellingServer.salesmanId,
          showName: sellingServer.getTheVCardSync().name,
        },
        userId: sessionUser.userId,
        userName: sessionUser.showName
      });
      console.log(this.data)
      this.loadShoppingCartList().then(()=>{
        this.getCouponById({
          status: 1,
          itemInfo: JSON.stringify(this.data.coupon_array)
        });
        const {useScore} = this.data
        if (useScore) this.calMoney()
      })
    })    
  },

  closepop() {
    var page = this;
    page.setData({
      ifshowS: false
    })
  },

  /**调用微信地址 */
  getwxAddress(id) {
    var page = this;
    wx.chooseAddress({
      success: function(res) {
        page.setData({
          waddress: res
        })
        wx.setStorageSync("waddress", res);
        page.addCustomerAddress(res);
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  /**调用发票信息 */
  getwxInvoice() {
    var page = this;
    wx.chooseInvoiceTitle({
      success(res) {
        if (res.type !== "undefined") {
          page.setData({
            invoiceType: 5,
            wx_invoice_type: res.type,
            wx_invoice_title: res.title,
            wx_invoice_tax_number: res.taxNumber,
            wx_invoice_company_address: res.companyAddress,
            wx_invoice_telephone: res.telephone,
            wx_invoice_bank_name: res.bankName,
            wx_invoice_bank_account: res.bankAccount,
          })
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  /**选择微信的地址后，将此地址增加到后台 */
  addCustomerAddress(res) {
    return JxbHttpClient.getClient().post({
      url: '/AppMaster/Account/addCustomerAddress',
      data: {
        provinceId: res.provinceName,
        cityId: res.cityName,
        areaId: res.countyName,
        name: res.userName,
        detailAddress: res.detailInfo,
        phone: res.telNumber,
        userId: this.data.userId,
        type: 3
      },
    }).then(resp=>{
      let addressId = resp._data.address_id;
      this.setData({
        addressId
      })
      wx.setStorageSync("addressId", addressId);
    }).catch(err=>{
      InteractionUtil.showNotice(err.message)
    })
  },
  /**如果获取微信地址授权的时候点击取消，此时跳转到设置页，将地址授权打开 */
  getAthuraty(id) {
    var page = this;
    wx.getSetting({
      success(res) {
        //判断授权信息里面有没有地址授权
        /**拒绝过地址授权，点击打开授权设置页面 */
        if (res.authSetting['scope.address'] == false) {
          wx.authorize({
            scope: 'scope.address',
            success(res) {
              console.log(res.errMsg); //用户授权后执行方法，如果用户之前拒绝过授权，再次调用authorize就不会进success，直接进fail
            },
            fail(res) { //用户拒绝授权后执行
              page.setData({
                ifshowS: true
              })
            }
          })
          return false;
        } else if (!res.authSetting['scope.address']) { /**之前没授权过 */
          wx.authorize({
            scope: 'scope.address',
            success(res) {
              page.getwxAddress(id); //用户授权后执行方法  
            },
            fail(res) {
              console.log(res);
            }
          })
        } else {
          page.getwxAddress(id);
        }
      },
      fail(res) {
        console.log('调用失败')
      }
    })
  },
  /**如果获取发票信息授权的时候点击取消，此时跳转到设置页，将发票信息授权打开 */
  getInvoice() {
    var page = this;
    wx.getSetting({
      success(res) {
        //判断授权信息里面有没有发票信息授权
        /**拒绝过发票信息授权，点击打开授权设置页面 */
        if (res.authSetting['scope.invoiceTitle'] == false) {
          wx.authorize({
            scope: 'scope.invoiceTitle',
            success(res) {
              console.log(res.errMsg); //用户授权后执行方法，如果用户之前拒绝过授权，再次调用authorize就不会进success，直接进fail
            },
            fail(res) { //用户拒绝授权后执行
              page.setData({
                ifshowS: true
              })
            }
          })
          return false;
        } else if (!res.authSetting['scope.invoiceTitle']) { /**之前没授权过 */
          wx.authorize({
            scope: 'scope.invoiceTitle',
            success(res) {
              page.getwxInvoice(); //用户授权后执行方法  
            },
            fail(res) {
              console.log(res);
            }
          })
        } else {
          page.getwxInvoice();
        }
      },
      fail(res) {
        console.log('调用失败')
      }
    })
  },

  // 查看优惠券
  coupon: function() {
    var coupon_array = JSON.stringify(this.data.coupon_array);
    wx.navigateTo({
      url: '/pages/coupon/use/use?coupon_array=' + coupon_array + '&is_useCoupon=showCanUseCoupon'
    })
  },

  // 满减-兑换
  cutPrinceByDiscount: function(e) {
    var page = this;
    var info = e.currentTarget.id;
    info = info.split("_");
    var id = info[0];
    var discount = parseInt(info[1]);
    var couponDkAmount = parseFloat(info[1]);
    var couponName = info[2];
    var couponInfo = '券:' + couponName.substr(0, 6) + ' 抵：￥' + couponDkAmount;
    // 满减下来金额如果小于0，等于0
    var actual_mon = page.data.sumShopPrice - discount;
    if (actual_mon < 0) {
      actual_mon = 0
    }
    page.setData({
      coupon_bind_id: id,
      sumMemberPrice: actual_mon.toFixed(2),
      couponInfo: couponInfo
    })
  },

  loadShoppingCartList: function() {
    let userId = SessionUserUtil.getInstanceSync().userId;
    return (new JxbHttpClient).get({
      url: '/AppMaster/PosCart/cartDetail',
      data: {
        userName: userId,
        item_id: this.data.checkedlis
      }
    }).then(jxbResp=>{
      let respData = jxbResp.data, products = respData.productsList, 
        points_use = respData.points_use, activity_list = respData.activity_list
      let itemids = [], limits = [];
      this.setData({
        sumcount: 0,
        sumMemberPrice: '',
        sumShopPrice: '',
        cartIds: 0,
        itemInfo: {
          'been': []
        },
        point: points_use
      });
      if (!products) {
        wx.switchTab({
          url: '/pages/order/index/index'
        })
      }
      for (let i = 0; i < activity_list.length; i++) {
        if (activity_list[i].activity_category == 6) {
          itemids = itemids.concat(activity_list[i].itemids);
        }
        if (activity_list[i].activity_category == 4) {
          limits = itemids.concat(activity_list[i].itemids);
        }
      }
      let sumcount = 0, sumMemberPrice = 0, sumShopPrice = 0, 
        cardIdstmp = products[0].cartId, coupon_array = [],
        itemInfo = this.data.itemInfo;
      for (let i = 0; i < products.length; i++) {
        let tmpitem = {}, coupon_json = {};
        let z = Common.contains(itemids, products[i].itemid), w = Common.contains(limits, products[i].itemid);
        if (z && w) {
          products[i].activity_list = ['秒杀', '限购']
        } else {
          if (z) {
            products[i].activity_list = ['秒杀'];
          }
          if (w) {
            products[i].activity_list = ['限购'];
          }
        }
        sumcount = sumcount + products[i].carNumber;
        sumMemberPrice = sumMemberPrice + products[i].carNumber * products[i].show_price;
        sumShopPrice = sumShopPrice + products[i].carNumber * products[i].show_price;
        if (i > 0) {
          cardIdstmp = cardIdstmp + '-' + products[i].cartId;
        }
        tmpitem.changemoney = products[i].show_price;
        tmpitem.count = products[i].carNumber;
        tmpitem.id = products[i].itemid;
        itemInfo.been.push(tmpitem);
        /**组一个json，作为优惠券跳转时带的参数 */
        coupon_json.item_id = products[i].itemid;
        coupon_json.count = products[i].carNumber;
        coupon_json.price = products[i].show_price;
        coupon_array.push(coupon_json);
      }
      respData.productsList = products
      // console.log(itemInfo)
      let sJson = JSON.stringify(itemInfo || {
        bean: []
      });
      //base64加密
      let str_base64_encode = (new fun_base64.Base64).encode(sJson);
      this.setData({
        shoppingCartList: respData,
        sumcount: sumcount,
        sumMemberPrice: sumMemberPrice.toFixed(2),
        sumShopPrice: sumShopPrice.toFixed(2),
        cartIds: cardIdstmp,
        itemInfo: str_base64_encode,
        coupon_array: coupon_array
      });
    }).catch(err=>{
      console.log(err)
      InteractionUtil.showNotice(err.message)
    })
  },
  getCouponById: function(data_json) {
    return JxbHttpClient.getClient().get({
        url:'AppMaster/Coupon/myCoupon',
        data:data_json
    }).then(jxbResp=>{
        let list = jxbResp.data?jxbResp.data.list:[],
          count = 0;
        for (var i = 0; i < list.length; i++) {
          if (list[i].can_use == 1) {
              count++;
          }
        }
        this.setData({
          coupon_name: count + "张可用"
      })
    }).catch(err=>{
        console.log('获取优惠券出错', err)
    })
  },
  goURL: function(e) {
    var ID = e.currentTarget.id.split("-"),
      page = this;
    if (ID[0] == 'customer') {
      wx.redirectTo({
        url: '/pages/customer/index/index?source=1'
      })
    } else if (ID[0] == 'address') {
      page.getAthuraty(ID[1]);
    } else if (ID[0] == 'dilivery') {
      wx.navigateTo({
        url: '/pages/dilivery/index/index?dilivery=' + ID[1]
      })
    } else if (ID[0] == 'invoice') {
      page.getInvoice();
    } else {
      console.log(ID);
      InteractionUtil.showNotice('即将开放，敬请期待！')
    }
  },
  buyerMessage: function(e) {
    // console.log(e.detail.value)
    this.setData({
      mark: e.detail.value,
    });
  },
  openPayAmountType: function() {
    var page = this;
    if (page.data.total_balance.is_show_wine_purchase) {
      page.setData({
        isHidePayAmountType: !page.data.isHidePayAmountType
      });
    } else {
      InteractionUtil.showNotice('只支持全额支付')
    }
  },
  guanbi: function() {
    var page = this;
    if (!page.data.isHidePayAmountType) {
      page.setData({
        isHidePayAmountType: true,
      });
      return;
    }

  },
  choosePayAmountTypeList: function(e) {
    var payType = e.currentTarget.id.split("-");
    var payAmountTypeId = payType[0];
    var payAmountTypeList = {
      1: '',
      5: ''
    };

    payAmountTypeList[payAmountTypeId] = 'cblue';

    this.setData({
      payAmountTypeId: payAmountTypeId,
      payAmountType: payType[1],
      payAmountTypeList: payAmountTypeList,
      isHidePayAmountType: !this.data.isHidePayAmountType
    });
  },
  goPay: function() {
    var page = this;
    if (!page.data.addressId && page.data.deliveryId * 1 === 2) {
      wx.hideLoading()
      InteractionUtil.showNotice('请选择收货地址');
      return false;
    }

    var data = {
      userId: page.data.userId,
      cartIds: page.data.cartIds,
      addressId: page.data.addressId,
      invoiceType: page.data.invoiceType,
      invoCustName: page.data.invoCustName,
      wx_invoice_type: page.data.wx_invoice_type,
      wx_invoice_title: page.data.wx_invoice_title,
      wx_invoice_tax_number: page.data.wx_invoice_tax_number,
      wx_invoice_company_address: page.data.wx_invoice_company_address,
      wx_invoice_telephone: page.data.wx_invoice_telephone,
      wx_invoice_bank_name: page.data.wx_invoice_bank_name,
      wx_invoice_bank_account: page.data.wx_invoice_bank_account,
      deliveryId: page.data.deliveryId,
      itemInfo: page.data.itemInfo,
      pay_amount_type: page.data.payAmountTypeId,
      will_pay_amount: page.data.will_pay_amount,
      mark: page.data.mark,
      coupon_bind_id: page.data.coupon_bind_id,
      use_points: page.data.useScore ? page.data.score : 0
    }
    InteractionUtil.showLoading(200, '订单生成中，请销后...')
    return JxbHttpClient.getClient().post({
      url: '/AppMaster/PosOrder/orderBorn',
      data: data,
    }).then(resp=>{
      // 关闭提示
      InteractionUtil.hideLoading(200)
      if (resp.data.totalMoney <= 0) {
        wx.redirectTo({
          url: '/pages/order/index/index?fromMy=0'
        });
        //switchTab
      } else {
        wx.redirectTo({
          url: '/pages/order/pay/pay?orderno=' + resp.data.orderSn + "&paymoney=" + resp.data.totalMoney + "&orders_id=" + resp.data.orderId
        });
      }
    }).catch(err=>{
      console.log(err);
      InteractionUtil.hideLoading()
      InteractionUtil.showAlert(err.message, '支付提醒')
    })
  },
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
  },

  onHide() {
    var page = this;
    page.closepop();
  },
  changeUseScore(e) {
    const {
      value
    } = e.detail
    if (value) {
      this.calMoney()
    } else {
      this.setData({
        score: 0,
        scoce_money: 0,
        useScore: false
      })
    }
  },
  calMoney () {
    let {
      point,
      sumMemberPrice,
      cutMoney
    } = this.data
    const {
      my_rank_points,
      use_points_item_price,
      points_price_max_proportion,
      points_use_proportion
    } = point
    let score = Math.min(my_rank_points, (use_points_item_price - cutMoney) * points_price_max_proportion / points_use_proportion)
    score = parseInt(score);
    const money = score * points_use_proportion
    this.setData({
      score: score,
      scoce_money: money,
      useScore: true
    })
  }
})